﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using Magicodes.Admin.WULINGAddresss.Dto;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using Abp.Linq.Extensions;
using Abp.Authorization;
using Magicodes.Admin.Authorization;
using Abp.Domain.Uow;

namespace Magicodes.Admin.WULINGAddresss
{
    [AbpAuthorize(AppPermissions.Pages_Manager_WulingAddressLibrary)]
    public class WULINGAddressAppService : AppServiceBase, IWULINGAddressAppService
    {
        private readonly IWULINGAddressRepository _wulingAddressRepository;


        public WULINGAddressAppService(IWULINGAddressRepository wulingAddressRepository)
        {
            _wulingAddressRepository = wulingAddressRepository;
        }

        public async Task DeleteAddressAsync(EntityDto<long> input)
        {
           await _wulingAddressRepository.DeleteAsync(input.Id);
        }

        public async Task<PagedResultDto<AddressListDto>> GetAddresssAsync(GetAddresssInput input)
        {
            var query = _wulingAddressRepository.GetAll()
                .WhereIf(
                !string.IsNullOrWhiteSpace(input.ServiceStationCode),
                u => u.ServiceStationCode.Contains(input.ServiceStationCode)
                )
                 .WhereIf(!string.IsNullOrWhiteSpace(input.ServiceStationName),
                u => u.ServiceStationName.Contains(input.ServiceStationName)).AsQueryable();




            var count = await query.CountAsync();

            var addresss = query
               .OrderBy(input.Sorting)
               .PageBy(input)
               .ToList();

            var addressListDtos = ObjectMapper.Map<IReadOnlyList<AddressListDto>>(addresss);



            return new PagedResultDto<AddressListDto>(
                count,
                addressListDtos
                );
        }
        [UnitOfWork]
        public async Task ImportFromExcel(IList<ImportAddressInputDto> importAddressInputDtos)
        { 
            var addresss = ObjectMapper.Map<List<WULINGAddress>>(importAddressInputDtos);

           await this._wulingAddressRepository.ImportFromExcel(addresss);

        }
    }
}
